package com.alperez.androidsmscamera.model;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;

/**
 * 
 * @author Stas
 *
 */
public class SuperRootAccount extends UserAccount {
	private SharedPreferences sPrefs;
	
	private boolean mAllowFullAccessByPassword;
	private boolean mAllowFullAccessBySource;
	
	public static SuperRootAccount getAccount(Context ctx) {
		SuperRootAccount account = new SuperRootAccount(ctx);
		account.restoreFromPrefs();
		return account;
	}
	
	/**
	 * Constructs default non initialized super root account.
	 * @param ctx
	 */
	public SuperRootAccount(Context ctx) {
		super(0, AccountType.ANONYMOUS_USER);
		super.accountType = AccountType.SUPER_ROOT_USER;
		sPrefs = ctx.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
	}
	
	/**
	 * Copy constructor
	 * @param acc
	 */
	public SuperRootAccount(Context ctx, SuperRootAccount acc) {
		super(acc);
		this.mAllowFullAccessByPassword = acc.mAllowFullAccessByPassword;
		this.mAllowFullAccessBySource = acc.mAllowFullAccessBySource;
		sPrefs = ctx.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
	}

	
	public void save() {
		JSONArray jPhones = new JSONArray();
		Iterator<String> itr = getSourcePhones().iterator();
		while (itr.hasNext()) {
			jPhones.put(itr.next());
		}
		Editor edt = sPrefs.edit();
		edt.putBoolean("allow_access_by_password", mAllowFullAccessByPassword)
			.putBoolean("allow_access_by_source", mAllowFullAccessBySource)
			.putString("password", getPassword())
			.putString("sources", jPhones.toString())
			.putBoolean("have_content", true);
		if (accountInfo != null) {
			edt.putLong("expired", accountInfo.getExpirationDate());
			edt.putString("first_name", accountInfo.getFirstName());
			edt.putString("last_name", accountInfo.getLastName());
			edt.putString("email", accountInfo.getEmail());
			edt.putBoolean("has_info", true);
		}
		edt.commit();
	}
	
	private void restoreFromPrefs() {
		if (!sPrefs.getBoolean("have_content", false)) {
			throw new IllegalStateException("Super root account has not been created yet!");
		}
		
		try {
			getSourcePhones().clear();
			JSONArray jPhones = new JSONArray(sPrefs.getString("sources", "[]"));
			for (int i=0; i<jPhones.length(); i++) {
				addSourcePhone(jPhones.getString(i));
			}
		} catch(JSONException e) {
			throw new IllegalStateException("Oops, something goes wrong! Error restoring JSON representation set of sources - " + e.getMessage());
		}
		setPassword(sPrefs.getString("password", null));
		mAllowFullAccessBySource = sPrefs.getBoolean("allow_access_by_source", false);
		mAllowFullAccessByPassword = sPrefs.getBoolean("allow_access_by_password", false);
		if (sPrefs.getBoolean("has_info", false)) {
			accountInfo = new AccountInfo();
			accountInfo.setExpirationDate(sPrefs.getLong("expired", 0));
			accountInfo.setFirstName(sPrefs.getString("first_name", ""));
			accountInfo.setLastName(sPrefs.getString("last_name", ""));
			accountInfo.setEmail(sPrefs.getString("email", ""));
		} else {
			accountInfo = null;
		}
		if ((getSourcePhones().size() == 0) || TextUtils.isEmpty(getPassword())) {
			throw new IllegalStateException("Oops, something goes wrong! Bad data for Super Root Account in preferences. nSources="+getSourcePhones().size()+", password="+getPassword());
		}
	}
	
	@Override
	public JSONObject toJSONObject() throws JSONException {
		JSONObject ret = super.toJSONObject();
		ret.put("full_access_psw", mAllowFullAccessByPassword);
		ret.put("full_access_src", mAllowFullAccessBySource);
		return ret;
	}
	
	@Override
	public String toJson() throws JSONException {
		return toJSONObject().toString();
	}
	
	@Override
	public void fromJson(String json) throws JSONException {
		super.fromJson(json);
		JSONObject jObj = new JSONObject(json);
		mAllowFullAccessByPassword = jObj.getBoolean("full_access_psw");
		mAllowFullAccessBySource = jObj.getBoolean("full_access_src");
	}
	
	
	public boolean isFullAccessByPasswordAllowed() {
		return mAllowFullAccessByPassword;
	}

	public void setFullAccessByPasswordAllowed(boolean mAllowFullAccessByPassword) {
		this.mAllowFullAccessByPassword = mAllowFullAccessByPassword;
	}

	public boolean isFullAccessBySourceAllowed() {
		return mAllowFullAccessBySource;
	}

	public void setFullAccessBySourceAllowed(boolean mAllowFullAccessBySource) {
		this.mAllowFullAccessBySource = mAllowFullAccessBySource;
	}
	
	@Override
	public void setAccountId(int accountId) {
		throw new IllegalStateException("Method setAccountId is not supported. Account ID makes no sense for Super Root Account.");
	}
	
	@Override
	public void setAccessLevel(int accessLevel) {
		throw new IllegalStateException("Method setAccessLevel() is not supported. Access level can not be changed for Super Root Account.");
	}

}
